package binary

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"math"
)

// formats 格式化字符串
var formats = map[int]string{
	10: "%d",
	16: "%02x",
}

// Text 获取文本
func Text(b []byte, base int) string {
	format := formats[base]
	buf := bytes.Buffer{}
	for _, v := range b {
		buf.WriteString(fmt.Sprintf(format, v))
	}
	return buf.String()
}

// IntToBytes 将64位带符号整数转换成字节数据
func IntToBytes(v int64, n int) []byte {
	if n == 0 {
		return nil
	}

	r := bytes.Buffer{}
	for i := 0; i < n; i++ {
		r.WriteByte(byte(v & 0xff))
		v >>= 8
	}
	return r.Bytes()
}

// Float32ToBytes 将32位浮点数转字节数组
func Float32ToBytes(v float32) []byte {
	bits := math.Float32bits(v)
	buf := make([]byte, 4)
	binary.LittleEndian.PutUint32(buf, bits)
	return buf
}
